#include "DmxDispatcher.h"

#include "LoopManager.h"



DmxDispatcher::DmxDispatcher(): mcommunicator("/dev/ttymxc4") {
    mcommunicator.initialize(250*1000);

//    mcommunicator.close();//for test

    const LoopSize_t size = MDConst::DEFAULT_INTERNAL_LOOP_COUNT;
    mcontrolInfoPtr.reset(new(size) LoopControlInfo{size, LoopStatus::ERROR}, LoopControlInfo::releaseMemory);
}

DmxDispatcher::~DmxDispatcher() {
    //dtor
}


bool DmxDispatcher::doWork() {
    const ssize_t readed = mcommunicator.read("dmx read error,", mbuffer, sizeof (mbuffer));
//    printf("readed:%zd,readed < sizeof (mbuffer):%d", readed, readed < (ssize_t)sizeof (mbuffer));
    if (readed < (ssize_t)sizeof (mbuffer)) {

        return true;
    }
    LoopSize_t size = mcontrolInfoPtr->length;

    std::string binaryString;
    StringUtility::dumpMemory(mbuffer, size + 2, "%u,", binaryString);
    printf("dmx512 readed:%zd, binary:%s\n", readed, binaryString.data());

    uint8_t* const  end = mbuffer + size + 2;
    for (uint8_t* iterator = mbuffer + 2; iterator != end; ++iterator){
       *iterator = (*iterator >> 7) + '0';
    }

    LoopManager& l = LoopManagerSingleton::instance();
    if (memcmp(mcontrolInfoPtr->loopStatus, mbuffer + 2, size)){
          mcontrolInfoPtr->setCommand(reinterpret_cast <const LoopStatus *>(mbuffer + 2), size);
          l.changeAutoLoopStatus(mcontrolInfoPtr);
    }



    return true;
}
